<template>
  <div class="flex items-center text-[13px]" @click.stop="show = !show">
    <svg-icon name="icon-date"></svg-icon>
    <span class="ml-[3px]">选择日期</span>
  </div>
  <van-calendar
    ref="calendarRef"
    :max-date="maxDate"
    :min-date="minDate"
    v-model:show="show"
    :default-date="date"
    type="range"
    @confirm="onConfirm"
  >
    <template #footer>
      <div class="grid grid-cols-2 gap-x-[10px] py-[10px]">
        <van-button size="small" round block @click="onCancel">取消</van-button>
        <van-button size="small" type="primary" round block @click="onConfirm"> 确定 </van-button>
      </div>
    </template>
  </van-calendar>
</template>

<script setup lang="ts">
import moment from "moment";

withDefaults(
  defineProps<{
    date: Date[];
  }>(),
  {}
);
const calendarRef = ref();
const minDate = computed(() => moment().subtract(1, "months").toDate());
const maxDate = computed(() => moment().add(1, "days").toDate());
const show = ref(false);
const emit = defineEmits(["update:date"]);

const onConfirm = () => {
  if (calendarRef.value) {
    const values = calendarRef.value?.getSelectedDate();
    emit("update:date", values.length == 1 ? [values[0], values[0]] : values);
  }
  show.value = false;
};

const onCancel = () => {
  emit("update:date", [moment().toDate(), moment().toDate()]);
  show.value = false;
};
</script>
